package com.techsoul.module.system.service.impl;

import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.enums.UserStatusEnum;
import com.techsoul.common.core.exception.BaseException;
import com.techsoul.common.core.pojo.vo.PostVo;
import com.techsoul.common.core.pojo.vo.RoleVo;
import com.techsoul.common.core.util.collection.SetUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.security.pojo.LoginUser;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.module.system.service.IMenuService;
import com.techsoul.module.system.service.IPostService;
import com.techsoul.module.system.service.IRoleService;
import com.techsoul.module.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 用户验证处理
 *
 * @author liuen
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPostService postService;

    @Autowired
    private IMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVo userVo = userService.findByUserName(username);
        if (StringUtils.isNull(userVo)) {
            log.info("登录用户：{} 不存在." , username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (ApiConstants.N.equals(userVo.getIsValid())) {
            log.info("登录用户：{} 已被删除." , username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatusEnum.DISABLE.getValue().equals(userVo.getStatus())) {
            log.info("登录用户：{} 已被停用." , username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        List<RoleVo> userRoles = roleService.findUserRoles(userVo.getId());
        Set<String> userPermissions = SetUtils.newHashSet(menuService.findUserPermissions(userVo.getId()));
        List<PostVo> posts = postService.findUserPosts(userVo.getId());
        return new LoginUser(userVo, userRoles, userPermissions, posts);
    }

}
